﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Web.Services.Protocols;

namespace SPWebShell
{
    [Cmdlet(VerbsCommon.Move,"SPItems")]
    public class MoveSPItems : PSCmdlet
    {
        ISPRepository _repos;
        public MoveSPItems()
        {
            this.Overwrite = false;
            _repos=new SPRepositoryImplementation(this.VerboseLogger,this.ErrorLogger);
        }
        protected override void ProcessRecord()
        {
            try
            {
                WriteVerbose("Start time: " + DateTime.Now.ToString());
                SPDoclibLocation locnSource = SPRepos.ResolveDoclibUrlFromPageUrl(this.Source);
                SPDoclibLocation locnDest = SPRepos.ResolveDoclibUrlFromPageUrl(this.Dest);

                SPReplicationResults result = SPRepos.Replicate(locnSource, locnDest, this.Overwrite);
                WriteObject(result);
                base.ProcessRecord();
            }
            catch (SoapException ex)
            {
                string message = ex.Detail.OuterXml;
                throw new Exception(message,ex);
            }
            finally
            {
                WriteVerbose("End time: " + DateTime.Now.ToString());
            }
        }
        private void VerboseLogger(string message)
        {
            this.WriteVerbose(message);
        }
        private void ErrorLogger(string message)
        {
            Exception ex=new Exception(message);
            WriteError(new ErrorRecord(ex,"", ErrorCategory.InvalidResult,null));
        }
        public void UnitTest()
        {
            WriteVerbose("time now is: " + DateTime.Now.ToString());
            WriteObject("hello world");
        }
        /// <summary>
        /// Should be the absolute URL to any item in the source document library or the URL to a view in the doc lib
        /// </summary>
        [Parameter(Mandatory=true)]
        [ValidateNotNullOrEmpty]
        public string Source { get; set; }
        
        /// <summary>
        /// Should be the absolute URL to any item in the destination document library or the URL to a view in the doc lib
        /// </summary>
        [Parameter(Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Dest { get; set; }
        
        [Parameter(Mandatory = false)]
        public int BatchSize { get; set; }

        [Parameter(Mandatory = false)]
        public bool Overwrite { get; set; }
        public ISPRepository SPRepos 
            { 
                get
                {
                    return _repos;
                }
                set
                {
                    _repos=value;
                }
            }
    }
}
